import Vue from "vue";
import Vuex from "vuex";
import app from "./app";
import user from "./user";

const DEPLOYLIST = "DEPLOYLIST";
const TASKLIST = "TASKLIST";
const USERLIST = "USERLIST";
const PERMISSLIST = "PERMISSLIST";

const mutations = {
  // 这里的data指提交时：
  // 从/api/login传回的user对象，其中包含name,messeage等信息
  [DEPLOYLIST](state, data) {
    state.deployList = data;
  },
  [TASKLIST](state, data) {
    state.taskList = data;
  },
  [USERLIST](state, data) {
    state.userList = data;
  },
  [PERMISSLIST](state, data) {
    state.permissList = data;
  }
};

import * as User from "../api/user";
import * as Task from "../api/task";

const actions = {
  // actions中的函数接受一个与store实例有相同属性和方法的context对像
  // 因此可以调用context中包含的state,getters以及mutations中定义的方法
  // userLogin(context){
  //   context.commit(types.LOGIN);
  // }
  // 使用es6的函数参数结构简化代码，可以直接将context.commit => commit使用
  // 在.vue文件中通过store.dispatch('userLogin') 即可触发状态改变了
  // 这里的data是因为提交mutations时需要获取从/api/login传回的user对象
  deployList({ commit }, data) {
    commit(DEPLOYLIST, data);
  },
  taskList({ commit }) {
    return Task.taskList().then(data => {
      if (data.code === 1) {
        commit(TASKLIST, data.data);
      }
    });
  },
  userList({ commit }) {
    return User.userkList().then(data => {
      if (data.code === 1) {
        data.data = data.data.map(item => {
          item.content = JSON.parse(item.content || "[]");
          return item;
        });
        commit(USERLIST, data.data);
      }
    });
  },
  permissList({ commit }) {
    return User.permissList().then(data => {
      if (data.code === 1) {
        data.data = data.data.map(item => {
          item.key = item.id;
          item.label = item.title;
          return item;
        });
        commit(PERMISSLIST, data.data);
      }
    });
  }
};
Vue.use(Vuex);
export default new Vuex.Store({
  state: {
    deployList: [],
    taskList: [],
    userList: [],
    permissList: []
  },
  mutations: mutations,
  actions: actions,
  modules: {
    app,
    user
  },
  getters: {
    sidebar: state => state.app.sidebar,
    size: state => state.app.size,
    device: state => state.app.device,
    token: state => state.user.token,
    avatar: state => state.user.avatar,
    name: state => state.user.name,
    introduction: state => state.user.introduction,
    roles: state => state.user.roles,
    permissions: state => state.user.permissions
  }
});
